<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="$t('pageUserManagement.accountPolicySettings')"
    width="500"
  >
    <el-form :model="form" :rules="rules">
      <el-space fill>
        <el-alert type="info" show-icon :closable="false">
          <p>
            {{
              $t('global.form.valueMustBeBetween', {
                min: 0,
                max: 65535,
              })
            }}
          </p>
        </el-alert>
        <el-form-item
          :label="$t('pageUserManagement.modal.maxFailedLoginAttempts')"
        >
          <el-input v-model="form.lockoutThreshold" autocomplete="off" />
        </el-form-item>
      </el-space>
      <el-form-item :label="$t('pageUserManagement.modal.userUnlockMethod')">
        <el-col>
          <el-radio-group v-model="radio" class="ml-4">
            <el-radio value="1" size="large">{{
              $t('pageUserManagement.modal.manual')
            }}</el-radio>
            <el-radio value="2" size="large">{{
              $t('pageUserManagement.modal.automaticAfterTimeout')
            }}</el-radio>
          </el-radio-group>
          <el-text class="mx-1 block" size="small">
            {{ $t('pageUserManagement.modal.timeoutDurationSeconds') }}
          </el-text>
          <el-input
            v-model="form.unlockMethod"
            autocomplete="off"
            :disabled="radio === '1'"
          />
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">{{
          $t('global.action.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ $t('global.action.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';

const {
  useVuelidate,
  required,
  minValue,
  maxValue,
  requiredIf,
  elementInputValidator,
} = useVuelidateTool();

const dialogFormVisible = ref(false);
defineExpose({ dialogFormVisible });

const emit = defineEmits(['ok']);
const props = defineProps<{
  settings: {
    lockoutThreshold: any;
    lockoutDuration: any;
  };
}>();

watch(
  () => props.settings,
  ({
    lockoutThreshold,
    lockoutDuration,
  }: {
    lockoutThreshold: any;
    lockoutDuration: any;
  }) => {
    form.lockoutThreshold = lockoutThreshold;
    form.unlockMethod = lockoutDuration ? 1 : 0;
    form.lockoutDuration = lockoutDuration ? lockoutDuration : null;
  },
);

const form = reactive({
  lockoutThreshold: 0,
  unlockMethod: 0,
  lockoutDuration: null,
});
const radio = ref('1');

const v$ = useVuelidate(
  {
    lockoutThreshold: {
      minValue: minValue(0),
      maxValue: maxValue(65535),
      required,
    },
    unlockMethod: { required },
    lockoutDuration: {
      minValue: function (value: number) {
        return form.unlockMethod === 0 || value > 0;
      },
      required: requiredIf(function () {
        return form.unlockMethod === 1;
      }),
    },
  },
  form,
);

const rules = computed(() => {
  return {
    newPassword: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'newPassword'),
      },
    ],
    confirmPassword: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'confirmPassword'),
      },
    ],
  };
});

const handleSubmit = () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;

  let lockoutThreshold;
  let lockoutDuration;
  console.log(v$.value.lockoutThreshold);
  if (v$.value.lockoutThreshold.$dirty) {
    lockoutThreshold = form.lockoutThreshold;
  }
  if (v$.value.unlockMethod.$dirty) {
    lockoutDuration = form.unlockMethod ? form.lockoutDuration : 0;
  }

  emit('ok', { lockoutThreshold, lockoutDuration });
  closeModal();
};
const closeModal = () => {
  nextTick(() => {
    dialogFormVisible.value = false;
  });
};
const resetForm = () => {
  // Reset form models
  form.lockoutThreshold = props.settings.lockoutThreshold;
  form.unlockMethod = props.settings.lockoutDuration ? 1 : 0;
  form.lockoutDuration = props.settings.lockoutDuration
    ? props.settings.lockoutDuration
    : null;
  v$.value.$reset(); // clear validations
  closeModal();
};
</script>
